package beautiful.butterfly.drds.data_exchange.util;

import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


class AsyncRetryableTask extends RetryableTask
{
    /**
     * 单位是秒数
     */
    private long timeout;
    private ThreadPoolExecutor threadPoolExecutor;

    public AsyncRetryableTask(long timeout, ThreadPoolExecutor threadPoolExecutor)
    {
        this.timeout = timeout;
        this.threadPoolExecutor = threadPoolExecutor;
    }


    @Override
    protected <T> T submit(Callable<T> callable) throws Exception
    {
        Future<T> future = threadPoolExecutor.submit(callable);
        try
        {
            return future.get(timeout, TimeUnit.MILLISECONDS);
        } catch (Exception e)
        {
            throw e;
        } finally
        {
            if (!future.isDone())
            {
                future.cancel(true);
            }
        }
    }
}
